from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
import re


class RbacMiddleware(MiddlewareMixin):
    '''
    权限控制的中间件
    '''

    def process_request(self, request):
        # 获取当前请求的url
        current_path = request.path_info

        # 白名单处理
        for item in settings.VALID_URL:
            if re.match(item, current_path):
                return None
        # 获取用户存在session中的权限
        permission_dict = request.session.get(settings.PERMISSION_SESSION_KEY)
        if not permission_dict:
            return redirect('/login/')
        # 面包屑导航条
        request.breadcrumb_list = [
            {'title': '首页', 'url': '/'},
        ]
        # 进行权限校验
        flag = False

        for item in permission_dict.values():
            id = item['id']
            pid = item['pid']
            pname = item['pname']
            reg = item['url']

            if re.match(reg, current_path):
                flag = True
                if pid:
                    request.current_menu_id = pid
                    request.breadcrumb_list.extend([
                        {'title': permission_dict[pname]['title'], 'url': permission_dict[pname]['url']},
                        {'title': item['title'], 'url': item['url']}
                    ])
                else:
                    request.current_menu_id = id
                    request.breadcrumb_list.extend([
                        {'title': item['title'], 'url': item['url']}
                    ])
                break
        if not flag:
            return HttpResponse('无权访问')
